package com.yloveg.impl;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.util.StringUtil;
import com.yloveg.common.AccessTokenUtil;
import com.yloveg.common.DateUtil;
import com.yloveg.dao.VTokenMapper;
import com.yloveg.entity.VToken;
import com.yloveg.service.VTokenService;

@Service
public class VTokenServiceImpl implements VTokenService {

	@Autowired
    private VTokenMapper vTokenMapper;

	@Override
	public int insertVToken(VToken record) {
		// TODO Auto-generated method stub
		record.setSts("Y");
		record.setCreateTime(new Date());
		return vTokenMapper.insert(record);
	}

	@Override
	public int updateByPrimaryKeySelective(VToken record) {
		// TODO Auto-generated method stub
		return vTokenMapper.updateByPrimaryKeySelective(record);
	}

	@Override
	public VToken selectByPrimaryKey(Integer id) {
		// TODO Auto-generated method stub
		return vTokenMapper.selectByPrimaryKey(id);
	}

	@Override
	public String selectNew() {
		// TODO Auto-generated method stub
		VToken vt = vTokenMapper.selectNew();
		if(vt!=null) {
			Date date = vt.getTime();
			Long time = DateUtil.getDatePoor(new Date(),date);
			if(time<6000000) {
				return vt.getToken();
			}else {
				String token ="";
				while(StringUtil.isEmpty(token)){
					token = AccessTokenUtil.getAccessTockenResult();
				}
				VToken vtNew = new VToken();
				vtNew.setTime(new Date());
				vtNew.setToken(token);
				this.insertVToken(vtNew);
				return token;
			}
		}else {
			String token = AccessTokenUtil.getAccessTockenResult();
			VToken vtNew = new VToken();
			vtNew.setTime(new Date());
			vtNew.setToken(token);
			this.insertVToken(vtNew);
			return token;
		}
	}
}
